//优惠码
(function() {
	var config = require("../_include/config");
	var db = require("../db/index");
	var md5 = require("../_include/md5");
	var helper = require("../_include/helper");
	var db_table_name = config.dbname.coupon;
	var db_id_prefix = config.dbIdPrefix.coupon;
	//构造函数
	var _con = function(info) {
		if (!info) {
			throwCusError("参数错误，优惠码信息不可为空");
		}
		var self = this;
		self._id = _con.getShortId();
		self.bus_id = info.bus_id;

		self.info = {};
		self.setInfo(info);

		self.create_time = +new Date;
		db.insert(db_table_name, self);
		console.log("生成了一个优惠码：", self._id);
	};

	module.exports = _con;

	//技能
	_con.prototype = require("./skill");
	_con.TYPE = {
		打折: 1,
		满减: 2,
		现金抵用: 3
	};

	//静态方法
	_con.get = function(Id) {
		var result = db.find_by_id(db_table_name, Id);
		if (result) {
			result.__proto__ = _con.prototype;
		}
		return result;
	};
	//获取一个段而且不重复的ID
	_con.getShortId = function() {
		do {
			var _id = (db_id_prefix + Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2)).substr(0,6);
		} while (db.find_by_id(db_table_name, _id))
		return _id
	};
	//生成默认的描述信息
	_con.getIntro = function(instance) {
		var result = "";
		var config = instance.info.config;
		switch (instance.info.type) {
			case _con.TYPE.打折:
				if (config.is_grads) {

				} else {
					result += "折扣：{0} 折\n".format(config.discount);
				}
				break;
			case _con.TYPE.满减:
				if (config.is_grads) {

				} else {
					result += "满 {0} 减 {1}\n".format(config.to, config.cut);
				}
				break;
			case _con.TYPE.现金抵用:
				if (config.is_grads) {

				} else {
					result += "抵用金额：{0}\n".format(config.vouchers);
				}
				break;
		}
		//关于有效期
		if (instance.diedline == Number.MAX_VALUE) {
			result += "永久有效\n";
		} else {
			if (instance.diedline > +new Date) {
				result += "有效期至：{0}\n".format(new Date.format("yyyy年MM月dd号 HH:mm"));
			} else {
				result += "已过期\n";
			}
		}
		//关于使用次数
		result += "可用次数：{0}\n".format(instance.times)
		return result;
	}

}());